import axios from "axios";
import { Message } from "element-ui";
import qs from "qs";
import { isJSON } from "./index";

// 基本实例
const service = axios.create({
  // baseURL: `${process.env.VUE_APP_API_URL_PREFIX}`,
});
// request 拦截器
// 对表单数据进行序列化
service.defaults.transformRequest = function(data, headers) {
  if (
    headers["Content-Type"] === "application/x-www-form-urlencoded" &&
    Object.prototype.toString(data) === "[object Object]"
  ) {
    data = qs.stringify(data);
  }
  return qs.stringify(data);
};

/**
 * @description 接口返回数据说明
 * @version 1.0.0
 * code 状态码 200 => success
 * data 请求返回数据
 * msg 返回信息
 */
// response 拦截器
service.interceptors.response.use(
  (response) => {
    if (isJSON(response.data)) {
      response.data = JSON.parse(response.data);
    }
    const code = response.data.code;

    if (code === "406") {
      Message.warning(response.data.message);
    }
    // 后台错误
    if (code === "500") {
      Message.error(response.data.message);
      return Promise.reject(new Error("request error"));
    }
    // 204
    if (code === "204") {
      Message.error({
        message: response.data.message,
        center: true,
      });
      return Promise.reject(new Error("request error"));
    }
    // -1 或者 -2
    if (code === "-1" || code === "-2") {
      Message.error({
        message: response.data.message,
        center: true,
      });
      return response.data;
    }
    // 其他状态 200、204
    if (response.data) {
      return response.data.data;
    }
    return response.data;
  },
  (error) => {
    Message.error(error.message);
    return Promise.reject(new Error(error));
  }
);

export default service;
